#! /usr/bin/env python3
import re
import markdown
import urllib
from markdown.preprocessors import Preprocessor
from markdown.extensions import Extension
from mdx_math import MathExtension


def temp_to_absolute(content, path, r_path, script_path):
    comp = re.compile(r'<img alt="(\w+?)" src="(.+?)"')
    match_list = re.findall(comp, content)
    global KPAN
    if '\\' in path:
        path = path.replace('\\', '/')
    for st in match_list:
        temp = st[1]
        src = st[1].replace('\\', '/')
        replace_path = path
        replace_path = replace_path.rstrip(replace_path.split('/')[-1]) + src
        replace_path = urllib.parse.quote(replace_path.replace(script_path + "/", ""))
        src = temp
        content = content.replace(src, replace_path)
    return content


def path_to_absolute(content, path):
    comp = re.compile(r'<a href="(.+?)"')
    match_list = re.findall(comp, content)
    if '\\' in path:
        path = path.replace('\\', '/')
    for st in match_list:
        if '#' in st:
            continue
        if 'javascript:void(0);' in st:
            continue
        if 'http:' in st:
            continue
        if 'https:' in st:
            continue
        temp = st
        src = st.replace('\\', '/')
        replace_path = path.rstrip(path.split('/')[-1]) + src
        replace_path = 'codeWeb.py?coder=' + urllib.parse.quote(replace_path) + '" target="_blank'
        src = temp
        content = content.replace(src, replace_path)
    return content


class CodePreprocessor(Preprocessor):
    def run(self, lines):
        new_line = list()
        for line in lines:
            if line[:2] == '**':
                new_line.append(line + '<br />')
            elif line[:2] == '![':
                new_line.append('<br />' + line + '<br />')
            else:
                new_line.append(line)
        return new_line


class CodeExtension(Extension):
    def __init__(self, configs={}):
        self.config = configs

    def extendMarkdown(self, md, md_globals):
        md.registerExtension(self)
        codepreprocessor = CodePreprocessor()
        md.preprocessors.add('codepreprocessor', codepreprocessor, '<normalize_whitespace')


def md_covert(md_path, r_path, script_path):
    configs = {}
    empty_line = CodeExtension(configs=configs)
    with open(md_path, 'r') as f:
        cont = f.read()
        html = markdown.markdown(cont, extensions=['markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.tables','markdown.extensions.toc', empty_line, MathExtension(enable_dollar_delimiter=True)])
        html = temp_to_absolute(html, md_path, r_path, script_path)
        html = path_to_absolute(html, r_path)
        return html
